import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router'
import Layout from '@/layout/index.vue'
import { getStorage } from '@/utils/auth'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
NProgress.configure({
  // 动画方式
  easing: 'ease',
  // 是否显示加载ico
  showSpinner: false,
  // 自动递增间隔
  trickleSpeed: 200,
  // 初始化时的最小百分比
  minimum: 0.3
})

// 静态路由
export const constantRoutes: Array<RouteRecordRaw> = [
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/login/index.vue'),
    meta: {
      hidden: true
    }
  }
]

// 异步路由
export const asyncRoutes: Array<RouteRecordRaw> = [
  {
    path: '/',
    component: Layout,
    meta: {
      title: '首页',
      icon: 'House',
      breadcrumb: false
    },
    redirect: '/',
    children: [
      {
        path: '/',
        name: 'Home',
        component: () => import('@/views/home/index.vue'),
        meta: {
          title: '首页',
          icon: 'House',
          breadcrumb: false
        }
      }
    ]
  },
  {
    path: '/order',
    component: Layout,
    redirect: '/order',
    meta: {
      title: '订单',
      icon: 'DocumentChecked',
      breadcrumb: true
    },
    children: [
      {
        path: '/order',
        name: 'Order',
        component: () => import('@/views/order/index.vue'),
        meta: {
          title: '订单列表',
          icon: 'DocumentChecked',
          breadcrumb: true
        }
      },
      {
        path: '/add',
        name: 'add',
        component: () => import('@/views/storage/index.vue'),
        meta: {
          title: '对象存储',
          icon: 'Folder',
          breadcrumb: true
        }
      }
    ]
  },
  {
    path: '/storage',
    component: Layout,
    redirect: '/storage',
    meta: {
      title: '对象存储',
      icon: 'Folder',
      breadcrumb: false
    },
    children: [
      {
        path: '/storage',
        name: 'storage',
        component: () => import('@/views/storage/index.vue'),
        meta: {
          title: '对象存储',
          icon: 'Folder',
          breadcrumb: true
        }
      }
    ]
  }
]
const router = createRouter({
  history: createWebHistory(),
  scrollBehavior: () => ({
    top: 0
  }),
  routes: constantRoutes.concat(asyncRoutes)
})
router.beforeEach((to, from, next) => {
  // 页面加载进度条
  if (to.name !== from.name) {
    NProgress.start()
  }

  const isLogin = getStorage('USER_TOKEN')
  const redirect: any = to.query.redirect || ''
  if (isLogin) {
    if (to.query.redirect) {
      next({
        path: redirect
      })
    } else {
      next()
    }
  } else if (to.path === '/login') {
    console.log('/login')
    next()
  } else {
    console.log('unauthed into login')
    next({
      path: '/login',
      query: { redirect: to.fullPath }
    })
  }
})
router.afterEach(() => {
  NProgress.done()
})
export default router
